#!/usr/bin/env python

import re
import base64
import sys
import commands

key = raw_input("Enter your 2-step authentication key as provided by Google: ")

if re.match(r'[^a-zA-Z2-9]', key):
    print "ERROR: 2-step key contains invalid characters, expecting only (A-Z,2-9)"
    sys.exit(1)

key = re.sub(r'[^a-zA-Z2-9]', '', key)

print "2-step key: "+key

if len(key) != 16:
    print "ERROR: 2-step key is not 16 characters (excluding spaces) in base 32 (A-Z,2-9)."
    sys.exit(1)

hex = base64.b32decode(re.sub(r'[^a-zA-Z2-9]', '', key), casefold=True).encode('hex')

print "hex key: "+hex

if len(hex) != 20:
    print "ERROR: calculated hex key is not 20 characters in base 16 (0-9,A-F)."
    sys.exit(1)

(status,pin) = commands.getstatusoutput('oathtool --totp ' + hex)

if status != 0:
    print "ERROR: "+pin
    sys.exit(1)

print "current pin: "+pin
